
const BASE_URL = 'http://192.168.31.242:9999/sshb';

/**
 * 封装 uni.request
 * @param {string} url 接口路径
 * @param {object} data 请求参数
 * @param {string} method 请求方法 GET/POST
 * @param {boolean} isShowLoading 是否显示 loading，默认 true
 * @returns {Promise}
 */
function request(url, data = {}, method = 'GET', isShowLoading = true) {
	const token = uni.getStorageSync('token'); 
	const header = {
		'content-type': 'application/json',
		...(token ? {
			authorization: 'Bearer ' + token
		} : {}),
	};

	if (isShowLoading) {
		uni.showLoading({
			title: '加载中...',
			mask: true,
		});
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: BASE_URL + url,
			data,
			method,
			header,
			success(res) {
				if (res.statusCode >= 200 && res.statusCode < 300) {
					resolve(res.data);
				} else {
					uni.showToast({
						title: '稍后再试~',
						icon: 'none'
					});
					reject(res.errMsg || '稍后再试~');
				}
			},
			fail(err) {
				uni.showToast({
					title: '网络异常',
					icon: 'none'
				});
				reject(err);
			},
			complete() {
				if (isShowLoading) {
					uni.hideLoading();
				}
			},
		});
	});
}

// GET 请求封装
export function $get(url, data = {}, isShowLoading = true) {
	return request(url, data, 'GET', isShowLoading);
}

// POST 请求封装
export function $post(url, data = {}, isShowLoading = true) {
	return request(url, data, 'POST', isShowLoading);
}